package com.example.myapplication.Style;

import android.content.Context;
import android.util.Xml;
import com.example.myapplication.Person;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import org.xmlpull.v1.XmlSerializer;

public class XmlGenerator {
  public void GeneratePersonXml(Context context,ArrayList<Person> personArrayList) {
    try {
      //创建一个XmlSerializer实例
      XmlSerializer serializer = Xml.newSerializer();

      //获取私有文件目录
      File folder=context.getFilesDir();
      File xmlFile = new File(folder, "person_value_text.xml");


      //创建一个Writer用于写入XML数据
      Writer writer = new OutputStreamWriter(new FileOutputStream(xmlFile));

      //设置writer给XmlSerializer
      serializer.setOutput(writer);

      //开始写入XML声明
      serializer.startDocument("UTF-8", true);


      //写入根元素
      serializer.startTag(null,"persons");

      for (int i = 0; i < personArrayList.size(); i++) {
        Person person = personArrayList.get(i);
        //开始写入子元素
        serializer.startTag(null, "person");

        serializer.startTag(null, "name");
        serializer.text(person.getName());
        serializer.endTag(null, "name");

        serializer.startTag(null, "job");
        serializer.text(person.getJob());
        serializer.endTag(null, "job");

        serializer.endTag(null, "person");
      }
      serializer.endTag(null, "persons");

      //结束XML文档
      serializer.endDocument();
      //关闭Writer
      writer.close();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}
